﻿using Common;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;


namespace enterprise.Website.Core.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    [LoginAuthorize]
    public class BannerController : ControllerBase
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public BannerController(SqlContext sqlContext, ICache cache, IWebHostEnvironment hostingEnvironment)
        {
            _cache = cache;
            _sqlContext = sqlContext;
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 获取轮播图管理
        /// </summary>
        /// <param name="languageId"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<Banner>> Get(int? languageId,int page = 1,int limit =10)
        {
            Expression<Func<Banner, LanguageType, bool>> where = (t, t1) => true;
            if (languageId.HasValue)
            {
                where = where.And((t, t1) => t.LanguageId == languageId.Value);
            }

            long Count = 0;
            var list = await _sqlContext.DB.Select<Banner, LanguageType>()
                .LeftJoin((t, t1) => t.LanguageId == t1.Id)
                .Where(where)
                .Page(page, limit)
                .Count(out Count)
                .OrderBy((t, t1) => t.LanguageId)
                .ToListAsync((t, t1) => new Banner
                {
                    Id = t.Id,
                    Img=t.Img,
                    Sort=t.Sort,
                    Url=t.Url,
                    LanguageId = t.LanguageId,
                    LanguageName = t1.Language
                });
            //计算总页数
            int pageCount = (Math.Ceiling(Count.ObjToDecimal() / limit.ObjToDecimal())).ObjToInt();
            return new PageModel<Banner>
            {
                count = Count,
                data = list,
                PageSize = limit,
                PageCount = pageCount,
                PageIndex = page,
                code = Count == 0 ? -1 : 0,
                msg = Count == 0 ? "暂无数据" : ""
            };
        }

        /// <summary>
        /// 新增轮播图
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody] Banner data)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (data != null)
            {
                var id= await _sqlContext.AddAsync(data);
                if (id > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.BannerKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 编辑轮播图
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult> Put(int id = 0, [FromBody] Banner data = null)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (data != null&& id>0)
            {
                var Count = await _sqlContext.UpdateAsync(data);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.BannerKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id = 0)
        {
            var result = new ApiResult { Success = false, Message = "保存成功" };
            if (id > 0)
            {
                var BannerInfo = await _sqlContext.QueryInfoAsync<Banner>(m => m.Id == id);
                if (BannerInfo != null)
                {
                    var Count = await _sqlContext.DeleteAsync<Banner>(m => m.Id == id);
                    if (Count > 0)
                    {
                        result.Success = true;
                        result.Message = "保存成功";
                        //如果有图标，则删除对应的图标
                        if (!BannerInfo.Img.IsNullOrWhiteSpace())
                        {
                            string filePath = _hostingEnvironment.WebRootPath + BannerInfo.Img;
                            if (System.IO.File.Exists(filePath))//如果存在此文件，将其删除
                            {
                                System.IO.File.Delete(filePath);
                            }
                        }
                        _cache.Remove($"{SystemConstConfig.BannerKey}_{BannerInfo.LanguageId}");
                    }
                }
            }
            return result;
        }
    }
}
